import { Ellipsis, Dialog, Input, Popover } from 'antd-mobile'
import styles from "./index.module.less"
import { DeleteOutline, EditSOutline, TravelOutline, AppOutline, LockFill, MoreOutline, DownOutline, UpOutline } from 'antd-mobile-icons'
import { worldType } from '@/utils/constant'
import classNames from 'classnames/bind';
import { useState } from 'react';
import { createChat } from '@/service/chat';
import { showSuccessToast, showErrorToast } from '@/utils/customToast';

const { deleteWorldBook, publishWorldRole } = $globalServicer('world')
const ItemCrad = (props) => {
  const { handleRefresh } = props
  const customNavigate = $globalNavigate()
  const [dropdownVisible, setDropdownVisible] = useState(false)
  const [isExpanded, setIsExpanded] = useState(false) // 控制描述展开/收起状态
  
  const handleDelete = (id) => {
    Dialog.confirm({
      content: '是否删除该智能体?',
      className: 'header-nav-dialog',
      confirmText: '确认',
      cancelText: '取消',
      closeOnAction: true,
      closeOnMaskClick: true,
      onConfirm: async () => {
        deleteWorldBook({ id }).then(res => {
          showSuccessToast('删除成功');
          handleRefresh && handleRefresh()
        })
      },
    })
  }
  
  const handlePush = (id) => {
    let inputValue = ''; // 用于存储输入值
    Dialog.confirm({
      content: (
        <div>
          <p>请输入推荐理由：</p>
          <Input
            placeholder="请输入推荐理由（最多50字）"
            maxLength={50}
            onChange={(val) => {
              inputValue = val; // 保存输入的值
            }}
            style={{
              '--font-size': '14px',
              marginTop: '8px',
            }}
          />
        </div>
      ),
      cancelText:
        <div className={styles.cancelClass}>
          取消
        </div>,
      confirmText: <div className={styles.confirmClass}>确认</div>,
      onConfirm: async () => {
        console.log({ id, push_reason: inputValue })
        publishWorldRole({ id, push_reason: inputValue }).then(res => {
          console.log(`------res`, res)
          showSuccessToast('推送成功');
        }).catch(err => {
          showErrorToast('推送失败');
        })
      },
    })
  }

  const handleEdit = () => {
    if (props.type === 1) {
      // 角色卡
      customNavigate(`/world/createRoleAndWorld?id=${props?.id}&type=edit`) 
    } else if (props.type === 2) {
      // 世界卡
      customNavigate(`/world/createMixRoleWorld?id=${props?.id}&type=edit`)
    } else if (props.type === 3) {
      // 无限卡
      customNavigate(`/world/createPremiumCard?id=${props?.id}&type=edit`)
    }
  }

  const handleChat = async () => {
    if (props.chat === null) {
      try {
        // 调用 createChat 接口创建聊天组
        const res = await createChat({ role_id: props?.id });
        if (res.chat_id) {
          // 创建成功后导航到聊天详情页面
          customNavigate(`/chatDetail?chatId=${res.chat_id}`);
        } else {
          showErrorToast('创建聊天失败，请重试');
        }
      } catch (error) {
        console.error('创建聊天失败:', error);
        showErrorToast('创建聊天失败，请重试');
      }
    } else {
      customNavigate(`/chatDetail?chatId=${props?.chat?.id}`)
    }
  }

  // 处理描述展开/收起
  const handleToggleExpand = () => {
    setIsExpanded(!isExpanded)
  }

  const dropdownActions = [
    {
      key: 'edit',
      text: '编辑'
    },
    {
      key: 'upload',
      text: '上传'
    }
  ]

  return (
    <div className={styles.card}>
      <div className={styles.cardImage}>
        <div
          className={styles.itemImage}
          style={{ backgroundImage: `url(${props.cover})`, backgroundSize: 'cover' }}
        >
          {/*<span className={classNames(props.type === 1 ? styles.defaultWorldBgc : props.type === 3 ? styles.infiniteWorld : styles.mixWorldBgc, styles.classifyWorld)}>*/}
          {/*  {worldType[props.type]}*/}
          {/*</span>*/}
          {/*{props.publish_type === 2 && <span className={styles.publishIcon}></span>}*/}
        </div>
      </div>
      
      <div className={styles.cardContent}>
        <div className={styles.cardHeader}>
          <h2 className={styles.cardTitle}>{props?.name}</h2>
          <button className={styles.deleteBtn} onClick={() => handleDelete(props?.id)}>
            删除
          </button>
        </div>
        
        <p className={styles.cardSubtitle}>
          {(props?.original_creator_id === 0 && !props?.original_creator_name) 
            ? 'AI物语' 
            : (props?.original_creator_name || props?.user_name || '开发者')}
        </p>
        
        <p className={classNames(styles.cardDescription, {
          [styles.expanded]: isExpanded
        })}>
          {props?.description || '暂无描述'}
        </p>
        
        <div className={styles.cardActions}>
          {/* 只有 publish_type 等于 1 时才显示 ... 按钮 */}
          {props.publish_type === 1 && (
            <div className={styles.relative}>
              <Popover.Menu
                actions={dropdownActions}
                placement='top-start'
                trigger='click'
                onAction={(action) => {
                  if (action.key === 'edit') {
                    handleEdit();
                  } else if (action.key === 'upload') {
                    customNavigate(`/publishCard?id=${props?.id}`);
                  }
                }}
              >
                <button className={styles.iconBtn}>
                  <MoreOutline />
                </button>
              </Popover.Menu>
            </div>
          )}
          
          <button className={styles.iconBtn} onClick={handleToggleExpand}>
            {isExpanded ? <UpOutline /> : <DownOutline />}
          </button>
          
          <button className={styles.dialogBtn} onClick={handleChat}>
            对话
          </button>
        </div>
      </div>
    </div>
  );
};

export default ItemCrad;
